package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.WeiboMapper;
import com.tedu.weibo.pojo.dto.WeiboDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.entity.Weibo;
import com.tedu.weibo.pojo.vo.WeiboDetailVO;
import com.tedu.weibo.pojo.vo.WeiboIndexVO;
import com.tedu.weibo.result.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

import static com.tedu.weibo.result.Status.NOT_LOGIN;
import static com.tedu.weibo.result.Status.OPERATION_SUCCESS;

@Api(tags = "微博模块")
@RestController
@RequestMapping("v1/weibo")
@Validated
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @ApiOperation(value = "发布微博")
    @PostMapping("/insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        User user = (User) session.getAttribute("user");
        if(user == null){
            return new JsonResult(NOT_LOGIN);
        }
        Weibo weibo = new Weibo();
        weibo.setContent(weiboDTO.getContent());
        weibo.setUserId(user.getId());
        weibo.setCreated(new Date());
        weiboMapper.insert(weibo);
        return JsonResult.success();
    }

    @ApiOperation(value = "查询微博列表")
    @GetMapping ("/selectIndex")
    public JsonResult selectIndex(){
        return JsonResult.success(weiboMapper.selectIndex());
    }


    @ApiOperation(value = "查询微博详情")
    @GetMapping("/selectById")
    @ApiImplicitParam(name = "id",value = "微博id",required = true,example = "1",dataType = "int")
    public JsonResult selectById(@Range(min = 1,max = 99999,message = "微博 id 必须大于 0") @RequestParam Integer id){
        if(id == null || id < 0){
            throw new IllegalArgumentException("微博 id 不正确");
        }
        return JsonResult.success(weiboMapper.selectById(id));
    }
}
